package com.sky.service.impl;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.OrderStatusReminderConstant;
import com.sky.constant.OrderTypeConstant;
import com.sky.context.BaseContext;
import com.sky.dto.*;
import com.sky.dto.mapper.OrdersDTOMapper;
import com.sky.dto.mapper.ShoppingCartDTOMapper;
import com.sky.entity.*;
import com.sky.exception.*;
import com.sky.mapper.*;
import com.sky.result.PageResult;
import com.sky.service.OrdersService;
import com.sky.utils.HttpClientUtil;
import com.sky.utils.WeChatPayUtil;
import com.sky.vo.*;
import com.sky.websocket.WebSocketServer;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author luo20
 * @description 针对表【orders(订单表)】的数据库操作Service实现
 * @createDate 2025-07-22 13:24:24
 */
@Service
@Slf4j
public class OrdersServiceImpl extends ServiceImpl<OrdersMapper, Orders>
        implements OrdersService {
    @Autowired
    private OrdersMapper ordersMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private ShoppingCartMapper shoppingCartMapper;
    @Autowired
    private OrdersDTOMapper ordersDTOMapper;
    @Autowired
    private AddressBookMapper addressBookMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WeChatPayUtil weChatPayUtil;
    @Autowired
    private ShoppingCartDTOMapper shoppingCartDTOMapper;
    @Autowired
    private WebSocketServer webSocketServer;

    @Value("${sky.shop.address}")
    private String shopAddress;
    @Value("${sky.baidu.ak}")
    private String ak;

    private final static String CANCEL_REASON = "用户取消";

    @Override
    @Transactional(rollbackFor = Exception.class)
    public OrderSubmitVO submitOrder(OrdersSubmitDTO ordersSubmitDTO) {

        // 处理各种业务异常(地址簿为空，购物车数据为空)
        AddressBook addressBook = addressBookMapper.selectById(ordersSubmitDTO.getAddressBookId());
        if (ObjectUtils.isEmpty(addressBook)) {
            // 地址簿为空
            throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }
        // 检查用户的收货地址是否超出配送范围
        checkOutOfRange(addressBook.getCityName()+addressBook.getDistrictName()+addressBook.getDetail());
        // 根据当前用户查询购物车数据是否为空
        // 获取用户id
        Long userId = BaseContext.getCurrentId();
        ShoppingCart shoppingCart = new ShoppingCart()
                .setUserId(userId);
        List<ShoppingCart> shoppingCartList = shoppingCartMapper.list(shoppingCart);
        if (CollectionUtils.isEmpty(shoppingCartList)) {
            // 当前用户的购物车数据为空
            throw new ShoppingCartBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }
        // 向订单表插入一条数据
        // dto -> entity
        Orders orders = ordersDTOMapper.toOrders(ordersSubmitDTO);
        // 待付款
        orders.setStatus(Orders.PENDING_PAYMENT);
        // 订单号
        orders.setNumber(UUID.randomUUID().toString() + System.currentTimeMillis());
        // 用户id
        orders.setUserId(userId);
        // 设置下单时间
        orders.setOrderTime(LocalDateTime.now());
        // 支付状态
        orders.setPayStatus(Orders.UN_PAID);
        // 手机号
        orders.setPhone(addressBook.getPhone());
        // 地址
        orders.setAddress(addressBook.getDetail());
        // 用户名称
        orders.setUserName(userMapper.selectById(userId).getName());
        // 收货人
        orders.setConsignee(addressBook.getConsignee());
        // 插入订单数据
        ordersMapper.saveOrder(orders);
        // 判断该订单id是否存在
        if (orders.getId() == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        // 向订单明细表插入多条数据
        List<OrderDetail> orderDetailList = shoppingCartList.stream().map(s -> {
            OrderDetail ordersDetail = new OrderDetail();
            ordersDetail.setOrderId(orders.getId());
            ordersDetail.setDishId(s.getDishId());
            ordersDetail.setSetmealId(s.getSetmealId());
            ordersDetail.setName(s.getName());
            ordersDetail.setImage(s.getImage());
            ordersDetail.setDishFlavor(s.getDishFlavor());
            ordersDetail.setNumber(s.getNumber());
            ordersDetail.setAmount(s.getAmount());
            return ordersDetail;
        }).toList();
        Integer orderDetailResult = orderDetailMapper.saveBath(orderDetailList);
        if (orderDetailResult != orderDetailList.size()) {
            throw new OrderBusinessException(MessageConstant.ADD_ORDERS_FAILED);
        }
        // 清空当前用户的购物车数据
        Integer clearCartResult = shoppingCartMapper.delCart(new ShoppingCart().setUserId(userId));
        if (clearCartResult != shoppingCartList.size()) {
            throw new DeletionCartFailedException(MessageConstant.CART_CLEAN_FAILED);
        }
        // 封装VO返回结果
        return OrderSubmitVO.builder()
                .id(orders.getId())
                .orderNumber(orders.getNumber())
                .orderAmount(orders.getAmount())
                .orderTime(orders.getOrderTime())
                .build();
    }
    /**
     * 检查客户的收货地址是否超出配送范围
     * @param address
     */
    private void checkOutOfRange(String address) {
        Map map = new HashMap();
        map.put("address",shopAddress);
        map.put("output","json");
        map.put("ak",ak);

        //获取店铺的经纬度坐标
        String shopCoordinate = HttpClientUtil.doGet("https://api.map.baidu.com/geocoding/v3", map);

        JSONObject jsonObject = JSON.parseObject(shopCoordinate);
        if(!jsonObject.getString("status").equals("0")){
            throw new OrderBusinessException("店铺地址解析失败");
        }

        //数据解析
        JSONObject location = jsonObject.getJSONObject("result").getJSONObject("location");
        String lat = location.getString("lat");
        String lng = location.getString("lng");
        //店铺经纬度坐标
        String shopLngLat = lat + "," + lng;

        map.put("address",address);
        //获取用户收货地址的经纬度坐标
        String userCoordinate = HttpClientUtil.doGet("https://api.map.baidu.com/geocoding/v3", map);

        jsonObject = JSON.parseObject(userCoordinate);
        if(!jsonObject.getString("status").equals("0")){
            throw new OrderBusinessException("收货地址解析失败");
        }

        //数据解析
        location = jsonObject.getJSONObject("result").getJSONObject("location");
        lat = location.getString("lat");
        lng = location.getString("lng");
        //用户收货地址经纬度坐标
        String userLngLat = lat + "," + lng;

        map.put("origin",shopLngLat);
        map.put("destination",userLngLat);
        map.put("steps_info","0");

        //路线规划
        String json = HttpClientUtil.doGet("https://api.map.baidu.com/directionlite/v1/driving", map);

        jsonObject = JSON.parseObject(json);
        if(!jsonObject.getString("status").equals("0")){
            throw new OrderBusinessException("配送路线规划失败");
        }

        //数据解析
        JSONObject result = jsonObject.getJSONObject("result");
        JSONArray jsonArray = (JSONArray) result.get("routes");
        Integer distance = (Integer) ((JSONObject) jsonArray.get(0)).get("distance");

        if(distance > 5000){
            //配送距离超过5000米
            throw new OrderBusinessException("超出配送范围");
        }
    }

    /**
     * 订单支付
     *
     * @param ordersPaymentDTO
     * @return
     */
    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();
        User user = userMapper.selectById(userId);

        // 调用微信支付接口，生成预支付交易单
        JSONObject jsonObject = weChatPayUtil.pay(
                ordersPaymentDTO.getOrderNumber(), // 商户订单号
                new BigDecimal(0.01), // 支付金额，单位 元
                "苍穹外卖订单", // 商品描述
                user.getOpenid() // 微信用户的openid
        );

        if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
            throw new OrderBusinessException("该订单已支付");
        }

        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
        vo.setPackageStr(jsonObject.getString("package"));

        return vo;
    }

    /**
     * 支付成功，修改订单状态
     *
     * @param outTradeNo
     */
    public void paySuccess(String outTradeNo) {

        // 根据订单号查询订单
        Orders ordersDB = ordersMapper.getByNumber(outTradeNo);

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();

        ordersMapper.updateOrder(orders);

        // 通过websocket向客户端浏览器推送消息 type orderId content
        Map<String, Object> map = new HashMap<>();
        map.put("type", OrderTypeConstant.ORDER_REMINDER);// 1来单提醒 2客户催单
        map.put("orderId", ordersDB.getId());
        map.put("content", "订单号：" + outTradeNo);

        String json = JSON.toJSONString(map);
        webSocketServer.sendToAllClient(json);
    }

    @Override
    public OrderDetailVO getOrderDetail(Long id) {
        List<OrderDetailVO> orderDetailVO = ordersMapper.getOrderDetail(new Orders().setId(id));
        if (ObjectUtils.isEmpty(orderDetailVO.get(0))) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        return orderDetailVO.get(0);
    }

    @Override
    public void cancelOrder(Long id) {
        // 查询当前订单是否存在
        Orders orderDB = confirmOrder(id);
        // 订单状态 1待付款 2待接单 3已接单 4派送中 5已完成 6已取消
        if (orderDB.getStatus() > 2) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        // 存在就改变订单状态为6-已取消
        Orders order = Orders.builder()
                .id(id)
                // 支付状态修改为 退款
                .payStatus(Orders.REFUND)
                // 更新订单状态、取消原因、取消时间
                .status(Orders.CANCELLED)
                .cancelReason(CANCEL_REASON)
                .cancelTime(LocalDateTime.now())
                .build();
        ordersMapper.updateOrder(order);
    }

    @Override
    public PageResult<OrderDetailVO> historyOrders(OrdersPageQueryDTO orderPageQueryDTO) {
        // 开启分页
        PageHelper.startPage(orderPageQueryDTO.getPage(), orderPageQueryDTO.getPageSize());
        // 根据订单状态查询订单数据
        List<OrderDetailVO> orderDetailVOList = ordersMapper.getOrderDetail(new Orders().setStatus(orderPageQueryDTO.getStatus()).setUserId(BaseContext.getCurrentId()));
        // 封装VO
        Page<OrderDetailVO> orderDetailVOPage = (Page<OrderDetailVO>) orderDetailVOList;
        // 返回结果
        return PageResult.<OrderDetailVO>builder()
                .total(orderDetailVOPage.getTotal())
                .records(orderDetailVOPage.getResult())
                .build();
    }

    @Override
    public void repetition(Long id) {
        // 判断订单是否存在
        Orders order = confirmOrder(id);
        // 获取当前用户
        Long userId = order.getUserId();
        // 根据订单id查询当前订单明细详情
        List<OrderDetail> orderDetailList = orderDetailMapper.getOrderDetailByOrderId(id);
        // 判断当前订单明细详情是否存在
        if (CollectionUtils.isEmpty(orderDetailList)) {
            throw new OrderBusinessException(MessageConstant.ORDER_DETAIL_NOT_FOUND);
        }
        List<ShoppingCart> shoppingCartList = orderDetailList.stream().map(orderDetail -> {
            // 将原订单详情里面的菜品信息重新复制到购物车对象中
            ShoppingCart shoppingCart = shoppingCartDTOMapper.orderDetailToShoppingCart(orderDetail);
            shoppingCart.setUserId(userId);
            shoppingCart.setCreateTime(LocalDateTime.now());
            return shoppingCart;
        }).toList();
        // 批量保存到购物车
       Integer saveBathResult = shoppingCartMapper.saveBatch(shoppingCartList);
       if (saveBathResult != shoppingCartList.size()){
           throw new OrderBusinessException(MessageConstant.ADD_SHOPPING_CART_FAILED);
       }
    }

    // 查询当前订单是否存在
    public Orders confirmOrder(Long id) {
        Orders order = ordersMapper.getOrderById(id);
        if (ObjectUtils.isEmpty(order)) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        return order;
    }

    @Override
    public void reminder(Long id) {
        Orders order = confirmOrder(id);
        // ❌ 状态1 - 待付款：用户自己还没付款，无需催单
        // ❌ 状态5 - 已完成：订单已完成，无需催单
        // ❌ 状态6 - 已取消：订单已取消，无法催单
        // ❌ 状态7 - 退款：订单在退款流程中，无法催单
        if (Objects.equals(order.getStatus(), Orders.PAID)) {
            throw new OrderBusinessException(OrderStatusReminderConstant.PENDING_PAYMENT);
        } else if (Objects.equals(order.getStatus(), Orders.COMPLETED)) {
            throw new OrderBusinessException(OrderStatusReminderConstant.COMPLETED);
        } else if (Objects.equals(order.getStatus(), Orders.CANCELLED)) {
            throw new OrderBusinessException(OrderStatusReminderConstant.CANCELLED);
        } else if (Objects.equals(order.getStatus(), Orders.REFUNDING)) {
            throw new OrderBusinessException(OrderStatusReminderConstant.REFUNDING);
        }
        // 通过websocket向客户端浏览器推送消息 type orderId content
        Map<String, Object> map = new HashMap<>();
        map.put("type", OrderTypeConstant.RUSH_ORDER);// 1来单提醒 2客户催单
        map.put("orderId", order.getId());
        map.put("content", "订单号：" + order.getNumber());

        String json = JSON.toJSONString(map);
        webSocketServer.sendToAllClient(json);
    }

    @Override
    public PageResult<OrderVO> conditionSearch(OrdersPageQueryDTO ordersPageQueryDTO) {
        // 开启分页
        PageHelper.startPage(ordersPageQueryDTO.getPage(), ordersPageQueryDTO.getPageSize());
        // 根据订单条件查询数据
        List<OrderVO> orderVOList = ordersMapper.conditionSearch(ordersPageQueryDTO);
        if (CollectionUtils.isNotEmpty(orderVOList)){
            // 根据订单数据判断订单菜品详情信息（订单中的菜品和数量）
            orderVOList.forEach(orderVO -> {
                //     获取订单菜品详情
                String orderDishs = orderVO.getOrderDetailList().stream().map(orderDetail -> {
                    // 将每一条订单菜品信息拼接为字符串（格式：宫保鸡丁*3；）
                    String orderDish = "";
                    if (orderDetail.getName() != null) {
                        orderDish = orderDetail.getName() + "*" + orderDetail.getNumber() + ";";
                    }
                    return orderDish;
                }).collect(Collectors.joining());
                //     将订单菜品信息封装到orderVO中
                orderVO.setOrderDishes(orderDishs);
            });
        }
        // 封装数据
        Page<OrderVO> orderVOPage = (Page<OrderVO>) orderVOList;
        // 返回结果
        return PageResult.<OrderVO>builder()
                .total(orderVOPage.getTotal())
                .records(orderVOPage.getResult())
                .build();
    }

    @Override
    public OrderStatisticsVO statistics() {
        // 获取待派送数量
        Integer confirmed = ordersMapper.countByStatus(Orders.CONFIRMED);
        // 获取派送中数量
        Integer deliveryInProgress = ordersMapper.countByStatus(Orders.DELIVERY_IN_PROGRESS);
        // 获取待接单数量
        Integer toBeConfirmed = ordersMapper.countByStatus(Orders.TO_BE_CONFIRMED);

        return OrderStatisticsVO.builder()
                .toBeConfirmed(toBeConfirmed)
                .confirmed(confirmed)
                .deliveryInProgress(deliveryInProgress)
                .build();
    }

    @Override
    public void delivery(Long id) {
        // 获取当前订单
        Orders order = ordersMapper.getOrderById(id);
        // 判断当前订单是否存在且状态是否为待派送 3
        if (order == null || !Objects.equals(order.getStatus(), Orders.CONFIRMED)){
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        // 根据订单id更新订单状态为派送中 4
        Integer updateOrder = ordersMapper.updateOrder(new Orders().setId(id).setStatus(Orders.DELIVERY_IN_PROGRESS));
        if (updateOrder <= 0){
            throw new OrderBusinessException(MessageConstant.UPDATE_STATUS_FAILED);
        }
    }

    @Override
    public void confirm(OrdersConfirmDTO ordersConfirmDTO) {
        // 获取当前订单
        Orders order = ordersMapper.getOrderById(ordersConfirmDTO.getId());
        // 判断当前订单是否存在且状态是否为待接单 2
        if (order == null || !Objects.equals(order.getStatus(), Orders.TO_BE_CONFIRMED)){
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        // 根据订单id更新订单状态为已接单 3
        Integer updateOrder = ordersMapper.updateOrder(new Orders().setId(ordersConfirmDTO.getId()).setStatus(Orders.CONFIRMED));
        if (updateOrder <= 0){
            throw new OrderBusinessException(MessageConstant.UPDATE_STATUS_FAILED);
        }
    }

    @Override
    public void cancel(OrdersCancelDTO ordersCancelDTO) throws Exception {
        // 获取当前订单
        Orders order = ordersMapper.getOrderById(ordersCancelDTO.getId());
        // 判断当前订单是否存在
        if (order == null){
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        //支付状态
        Integer payStatus = order.getPayStatus();
        if (Objects.equals(payStatus, Orders.PAID)) {
            //用户已支付，需要退款
            // String refund = weChatPayUtil.refund(
            //         order.getNumber(),
            //         order.getNumber(),
            //         new BigDecimal(0.01),
            //         new BigDecimal(0.01));
            // log.info("申请退款：{}", refund);
        }
        // 管理端取消订单需要退款，根据订单id更新订单状态、取消原因、取消时间
        Orders o = Orders.builder()
                .id(ordersCancelDTO.getId())
                .status(Orders.CANCELLED)
                .cancelReason(ordersCancelDTO.getCancelReason())
                .cancelTime(LocalDateTime.now())
                .build();
        Integer updateOrderResult = ordersMapper.updateOrder(o);
        if (updateOrderResult <= 0){
            throw new OrderBusinessException(MessageConstant.UPDATE_STATUS_FAILED);
        }

    }

    @Override
    public void rejection(OrdersRejectionDTO ordersCancelDTO) {
        // 获取当前订单
        Orders order = ordersMapper.getOrderById(ordersCancelDTO.getId());
        // 判断当前订单是否存在,且状态为待接单 2
        if (order == null || !Objects.equals(order.getStatus(), Orders.TO_BE_CONFIRMED)){
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        //支付状态
        Integer payStatus = order.getPayStatus();
        if (Objects.equals(payStatus, Orders.PAID)) {
            //用户已支付，需要退款
            // String refund = weChatPayUtil.refund(
            //         order.getNumber(),
            //         order.getNumber(),
            //         new BigDecimal(0.01),
            //         new BigDecimal(0.01));
            // log.info("申请退款：{}", refund);
        }
        // 管理端取消订单需要退款，根据订单id更新订单状态、取消原因、取消时间
        Orders o = Orders.builder()
                .id(ordersCancelDTO.getId())
                .status(Orders.CANCELLED)
                .rejectionReason(ordersCancelDTO.getRejectionReason())
                .cancelTime(LocalDateTime.now())
                .build();
        Integer updateOrderResult = ordersMapper.updateOrder(o);
        if (updateOrderResult <= 0){
            throw new OrderBusinessException(MessageConstant.UPDATE_STATUS_FAILED);
        }

    }

    @Override
    public void complete(Long id) {
        // 获取当前订单
        Orders orders = ordersMapper.getOrderById(id);
        // 判断订单是否存在且状态是否为4派送中
        if (orders == null || !Objects.equals(orders.getStatus(), Orders.DELIVERY_IN_PROGRESS)){
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        // 修改订单状态为5完成
        Orders o = Orders.builder()
                .id(id)
                .status(Orders.COMPLETED)
                .deliveryTime(LocalDateTime.now())
                .build();
        Integer updateOrder = ordersMapper.updateOrder(o);
        if (updateOrder <= 0) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
    }

}




